from flask import Flask, request, jsonify
from flask_cors import CORS
from tools.db import init_db
from models.models import User, Role, Permission, Order, OrderItem, Address, Tag
from models.crud_operations import UserService, OrderService, RoleService, PermissionService, TagService, AddressService
import datetime

app = Flask(__name__)
CORS(app)

# 初始化数据库
db = init_db(app)

@app.route('/api/init_data', methods=['POST'])
def init_sample_data():
    """初始化示例数据"""
    try:
        # 创建角色
        admin_role = RoleService.create_role('admin', '管理员角色')
        user_role = RoleService.create_role('user', '普通用户角色')
        
        # 创建权限
        user_read = PermissionService.create_permission('user_read', 'user', 'read')
        user_write = PermissionService.create_permission('user_write', 'user', 'write')
        order_read = PermissionService.create_permission('order_read', 'order', 'read')
        order_write = PermissionService.create_permission('order_write', 'order', 'write')
        
        # 为角色分配权限
        RoleService.assign_permission_to_role(admin_role.id, user_read.id)
        RoleService.assign_permission_to_role(admin_role.id, user_write.id)
        RoleService.assign_permission_to_role(admin_role.id, order_read.id)
        RoleService.assign_permission_to_role(admin_role.id, order_write.id)
        RoleService.assign_permission_to_role(user_role.id, order_read.id)
        
        # 创建用户
        admin_user = UserService.create_user('admin', 'admin@example.com', 'admin_password_hash')
        user1 = UserService.create_user('user1', 'user1@example.com', 'user1_password_hash')
        user2 = UserService.create_user('user2', 'user2@example.com', 'user2_password_hash')
        
        # 为用户分配角色
        UserService.assign_role_to_user(admin_user.id, admin_role.id)
        UserService.assign_role_to_user(user1.id, user_role.id)
        UserService.assign_role_to_user(user2.id, user_role.id)
        
        # 创建标签
        vip_tag = TagService.create_tag('VIP', '#FF6B6B', 'VIP用户标签')
        new_user_tag = TagService.create_tag('新用户', '#4ECDC4', '新注册用户标签')
        
        # 为用户添加标签
        UserService.assign_tag_to_user(user1.id, vip_tag.id)
        UserService.assign_tag_to_user(user2.id, new_user_tag.id)
        
        # 创建地址
        AddressService.create_address(
            user1.id, '张三', '13800138000', '广东省', '深圳市', '南山区', 
            '科技园南区', '518000', True
        )
        AddressService.create_address(
            user1.id, '张三', '13800138001', '广东省', '深圳市', '福田区', 
            '华强北街道', '518000', False
        )
        
        # 创建订单
        order1 = OrderService.create_order(user1.id, 'ORD001', 299.99, 'paid')
        order2 = OrderService.create_order(user1.id, 'ORD002', 199.50, 'pending')
        
        # 为订单添加订单项
        OrderService.add_order_item(order1.id, 'iPhone 15', 1, 299.99)
        OrderService.add_order_item(order2.id, 'MacBook Pro', 1, 199.50)
        
        return jsonify({
            "code": 200,
            "message": "示例数据初始化成功",
            "data": {
                "users": 3,
                "roles": 2,
                "permissions": 4,
                "tags": 2,
                "addresses": 2,
                "orders": 2
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"初始化数据失败: {str(e)}"
        }), 500

# 用户相关API
@app.route('/api/users', methods=['GET'])
def get_users():
    """获取所有用户"""
    try:
        users = UserService.get_all_users()
        return jsonify({
            "code": 200,
            "message": "获取用户列表成功",
            "data": [user.to_dict() for user in users]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取用户列表失败: {str(e)}"
        }), 500

@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """获取单个用户信息"""
    try:
        user = UserService.get_user_by_id(user_id)
        if user:
            return jsonify({
                "code": 200,
                "message": "获取用户信息成功",
                "data": user.to_dict()
            }), 200
        else:
            return jsonify({
                "code": 404,
                "message": "用户不存在"
            }), 404
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取用户信息失败: {str(e)}"
        }), 500

@app.route('/api/users/<int:user_id>/orders', methods=['GET'])
def get_user_orders(user_id):
    """获取用户的所有订单"""
    try:
        orders = UserService.get_user_orders(user_id)
        return jsonify({
            "code": 200,
            "message": "获取用户订单成功",
            "data": [order.to_dict() for order in orders]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取用户订单失败: {str(e)}"
        }), 500

@app.route('/api/users/<int:user_id>/addresses', methods=['GET'])
def get_user_addresses(user_id):
    """获取用户的所有地址"""
    try:
        addresses = UserService.get_user_addresses(user_id)
        return jsonify({
            "code": 200,
            "message": "获取用户地址成功",
            "data": [address.to_dict() for address in addresses]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取用户地址失败: {str(e)}"
        }), 500

@app.route('/api/users/<int:user_id>/roles', methods=['GET'])
def get_user_roles(user_id):
    """获取用户的所有角色"""
    try:
        roles = UserService.get_user_roles(user_id)
        return jsonify({
            "code": 200,
            "message": "获取用户角色成功",
            "data": [role.to_dict() for role in roles]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取用户角色失败: {str(e)}"
        }), 500

@app.route('/api/users/<int:user_id>/tags', methods=['GET'])
def get_user_tags(user_id):
    """获取用户的所有标签"""
    try:
        tags = UserService.get_user_tags(user_id)
        return jsonify({
            "code": 200,
            "message": "获取用户标签成功",
            "data": [tag.to_dict() for tag in tags]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取用户标签失败: {str(e)}"
        }), 500

# 角色相关API
@app.route('/api/roles', methods=['GET'])
def get_roles():
    """获取所有角色"""
    try:
        roles = RoleService.get_all_roles()
        return jsonify({
            "code": 200,
            "message": "获取角色列表成功",
            "data": [role.to_dict() for role in roles]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取角色列表失败: {str(e)}"
        }), 500

@app.route('/api/roles/<int:role_id>/permissions', methods=['GET'])
def get_role_permissions(role_id):
    """获取角色的所有权限"""
    try:
        permissions = RoleService.get_role_permissions(role_id)
        return jsonify({
            "code": 200,
            "message": "获取角色权限成功",
            "data": [permission.to_dict() for permission in permissions]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取角色权限失败: {str(e)}"
        }), 500

# 订单相关API
@app.route('/api/orders', methods=['GET'])
def get_orders():
    """获取所有订单"""
    try:
        orders = Order.query.all()
        return jsonify({
            "code": 200,
            "message": "获取订单列表成功",
            "data": [order.to_dict() for order in orders]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取订单列表失败: {str(e)}"
        }), 500

@app.route('/api/orders/<int:order_id>/items', methods=['GET'])
def get_order_items(order_id):
    """获取订单的所有订单项"""
    try:
        order_items = OrderService.get_order_items(order_id)
        return jsonify({
            "code": 200,
            "message": "获取订单项成功",
            "data": [item.to_dict() for item in order_items]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取订单项失败: {str(e)}"
        }), 500

# 标签相关API
@app.route('/api/tags', methods=['GET'])
def get_tags():
    """获取所有标签"""
    try:
        tags = TagService.get_all_tags()
        return jsonify({
            "code": 200,
            "message": "获取标签列表成功",
            "data": [tag.to_dict() for tag in tags]
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取标签列表失败: {str(e)}"
        }), 500

# 关系操作API
@app.route('/api/users/<int:user_id>/assign_role', methods=['POST'])
def assign_role_to_user(user_id):
    """为用户分配角色"""
    try:
        data = request.get_json()
        role_id = data.get('role_id')
        
        if UserService.assign_role_to_user(user_id, role_id):
            return jsonify({
                "code": 200,
                "message": "角色分配成功"
            }), 200
        else:
            return jsonify({
                "code": 400,
                "message": "角色分配失败"
            }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"角色分配失败: {str(e)}"
        }), 500

@app.route('/api/users/<int:user_id>/assign_tag', methods=['POST'])
def assign_tag_to_user(user_id):
    """为用户添加标签"""
    try:
        data = request.get_json()
        tag_id = data.get('tag_id')
        
        if UserService.assign_tag_to_user(user_id, tag_id):
            return jsonify({
                "code": 200,
                "message": "标签添加成功"
            }), 200
        else:
            return jsonify({
                "code": 400,
                "message": "标签添加失败"
            }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"标签添加失败: {str(e)}"
        }), 500

@app.route('/api/orders/<int:order_id>/add_item', methods=['POST'])
def add_order_item(order_id):
    """为订单添加订单项"""
    try:
        data = request.get_json()
        product_name = data.get('product_name')
        quantity = data.get('quantity')
        unit_price = data.get('unit_price')
        
        order_item = OrderService.add_order_item(order_id, product_name, quantity, unit_price)
        if order_item:
            return jsonify({
                "code": 200,
                "message": "订单项添加成功",
                "data": order_item.to_dict()
            }), 200
        else:
            return jsonify({
                "code": 400,
                "message": "订单项添加失败"
            }), 400
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"订单项添加失败: {str(e)}"
        }), 500

if __name__ == '__main__':
    print("🚀 启动Flask应用 (带数据库模型)")
    print("📝 功能特性:")
    print("   ✅ 一对多关系 (User-Order, User-Address, Order-OrderItem)")
    print("   ✅ 多对多关系 (User-Role, User-Tag, Role-Permission)")
    print("   ✅ 完整的CRUD操作")
    print("   ✅ 关系操作API")
    print("🔗 访问地址: http://localhost:5000")
    print("📊 初始化数据: POST http://localhost:5000/api/init_data")
    print("📈 获取用户: GET http://localhost:5000/api/users")
    app.run(debug=True, host='0.0.0.0', port=5000)

